import { useRequest } from 'ahooks'

import { useControllerRef } from '@/hooks/useAbortController'
import { useRequestSyncStorePlugin } from '@/hooks/useRequestSyncStorePlugin'
import { apiGetNoticeList } from './apis'
import { INotice, INoticeListReq } from './interface'
import { useBoundStore } from './store'

export const useNoticeList = () => {
  const controllerRef = useControllerRef()
  const requestSyncStorePlugin = useRequestSyncStorePlugin({
    onMaybeChange: request => useBoundStore.setState({ request }),
  })

  useRequest<INotice[], [INoticeListReq]>(
    async req => {
      controllerRef.current.abort()
      controllerRef.current = new AbortController()
      return apiGetNoticeList(req, controllerRef.current.signal)
    },
    {
      manual: true,
    },
    [requestSyncStorePlugin],
  )
}
